/*
 * $navTab v1.0 Copyright(c) 2016.6 by CSS WeidongWang
 */
function navTabSearch(form, navTabId){
	$navTab.submitForm(form);
	return false;
}
;(function($){
	var tabModel = {
			id:"",
			title:"",
			url:"",
			formParams:"",
			iframe:false,
			tabWidth:0,
			data:{}
	},
	config=function(tabInfo){
		tabInfo  = tabInfo||{};
		// 合并默认配置
		for( var i in tabModel )
		{
			if( tabInfo[i] === undefined ) tabInfo[i] = tabModel[i];
		}
		return tabInfo;
	},
	map = {},
			maxLength = 15,
			homeTabId,
			curTab,
			methods = {

				init: function(inTab){
					homeTabId = inTab.id;
					curTab  = inTab;
					map[curTab.id]=curTab;
					methods.initClick(curTab);
				},
				initTab: function(tabInfo){
					$li = $('<li id="myTabli' + tabInfo.id + '"><a title="'+tabInfo.title+'" tabid="' + tabInfo.id + '" href="#' + tabInfo.id + '"><i class="remove"></i><span>' + tabInfo.title + '</span></a></li>');
			    $ul.append($li);
			    $li.find('a .remove').on('click', methods.event.close);
				},
  			initClick: function(tabInfo){
					$a=$ul.find('[href="#' + tabInfo.id + '"]');
					$a.on('click', methods.event.click);
					tabInfo.tabWidth=$a.outerWidth(true);
					$more.next().append('<li id="moreBtnLi' + tabInfo.id + '"><a title="'+tabInfo.title+'" href="javascript:;">'+tabInfo.title.replaceAll('&nbsp;','').substr(0,16)+'</a></li>');
 					$more.next().on('click','li',function(){
          	var index=$more.next().find('li').index(this);
          	$ul.find('> li a').eq(index).click();
        	});
  				methods.contextMenu($a);
				}, 
        loadTab: function(tabInfo){
        	$('#'+tabInfo.id).remove();
        	if(tabInfo.iframe){
        		var ih = $content.height() - 5;
        		$content.append('<div id="' + tabInfo.id + '" class="tab-pane"><iframe src="' + tabInfo.url + '" style="margin:0;padding0;overflow:hidden;width:100%;height:' + ih + 'px;" frameborder="no" border="0" marginwidth="0" marginheight="0"></iframe></div>');
						if(tabInfo.id==curTab.id) methods.showTab();
        	}
        	else
						methods.ajaxFun(tabInfo);
				},
        ajaxFun: function(tabInfo){
        	if(tabInfo.id==curTab.id) blockUI($content);
        	$.post(tabInfo.url,tabInfo.formParams,function(data){
        		if(tabInfo.id==curTab.id) unblockUI($content);
           	$content.append('<div id="' + tabInfo.id + '" class="tab-pane">'+data+'</div>');
						if(tabInfo.id==curTab.id) methods.showTab();
					})
        },
				hideTab:function(){
	      	$('#'+curTab.id).hide();
	      },
				showTab:function(){
					$ul.find('[href="#' + curTab.id + '"]').tab('show');
	      	$('#'+curTab.id).show();
	      	$more.next().children().removeClass('active')
			$more.next().find('#moreBtnLi'+curTab.id).addClass('active');
			methods.scrollCurrent();
	      },
	      event: {
	        click: function(e) {
	         	var key=$(this).attr('tabid');
	          if(key == curTab.id)
	          	return;
						methods.hideTab();
						curTab = map[key];
	        	methods.showTab();
	        },
	        close: function(e) {
	          var key=$(this).parent().attr('tabid');
	          $navTab.closeTab(key);
	        }
      	},
        closeOther: function (key) {
        	for(tmpKey in map){
        		if(tmpKey!=key)
        			$navTab.closeTab(tmpKey);
					}
        },
        closeAll: function () {
        	for(tmpKey in map)
        		$navTab.closeTab(tmpKey);
        },
	      contextMenu: function($obj) {
	        $obj.contextMenu($ul.attr('context-menu'), {
			      callback: {
			      	'close': function(t) {
			      		$navTab.closeTab(t.attr('tabid'));
		          },
		          'closeOther': function(t) {
		            methods.closeOther(t.attr('tabid'));
		          },
		          'closeAll': function(t) {
		            methods.closeAll();
		          },
		          'reload': function(t) {
		            $navTab.refreshTab(t.attr('tabid'));
		          }
			      }
			    });
      	},
	    getNextTab : function(key) {
			var nextTabId = '', left = 1;
			for ( var tmpKey in map) {
				if (left < 1)
					return tmpKey;
				if (tmpKey == key)
					left--;
				else
					nextTabId = tmpKey;
			}
			if(!methods.isTabExist(nextTabId)){
				return methods.getNextTab(key);
			}
			return nextTabId;
		},
      	isTabExist:function(key){
      		if(!key)return false;
      		if(!map[key])return false;
      		var exist = $ul.find('[href="#' + map[key].id + '"]').length!=0 && $('#'+map[key].id).length!=0;
      		if(!exist){
      			delete map[key];
      		}
      		return exist;
      	},
	      scrollTab: function(iLeft){
//	    	  if(iLeft<0 
//	    			|| ($('.page-content').width()-$('.nav-tabs').width()-parseInt($('.nav-tabs').css('margin-right'))||0)<=0
//	    			){
//		    	  var tabcount = $('.nav-tabs li').length,
//		    	  tabwidth = ($('.page-content').width()-tabcount*2 - parseInt($('.nav-tabs').css('margin-right'))||0 )/tabcount;
//		    	  $('.nav-tabs li').each(function(i,v){
//		    		  $(v).width(tabwidth);
//		    	  });
//	    	  }else{
//	    		  
//	    		  var tabcount = $('.nav-tabs li').length;
//	    		  if(tabcount <=5 ){
//	    			  $('.nav-tabs li').each(function(i,v){
//	    				  $(v).width(150);
//	    			  });
//	    		  }
//	    	  }
	    	  var tabcount = $('.nav-tabs li').length;
	    	  if(tabcount>6){
			    	  var tabcount = $('.nav-tabs li').length,
			    	  tabwidth = ($('.page-content').width()-tabcount*2 - parseInt($('.nav-tabs').css('margin-right'))||0 )/tabcount;
			    	  $('.nav-tabs li').each(function(i,v){
			    		  $(v).width(tabwidth);
			    	  });
		    	  }else{
		    			  $('.nav-tabs li').each(function(i,v){
		    				  $(v).width(150);
		    			  });
		    		 }
	    		  //$ul.animate({ marginLeft: iLeft+'px' }, 200, function(){});
	      },
       currentPos: function(){
	      	var cw=0;
	      	for(tmpKey in map){
	      		tmpTab = map[tmpKey];
	      		cw+=tmpTab.tabWidth;
	      		if(tmpKey==curTab.id)
	      			break;
					}
					return cw;
	      },
	      scrollCurrent: function(){
	      	var barw = $module.width(); 
	      	var cw = methods.currentPos();
	      	methods.scrollTab(cw <= barw-15?0:(barw-cw-100));
	      }
    	};
 	$navTab = {
    event: function(){
      $('body').on('click','[target=cssTab]',function(){
		    var $this=$(this),
		    	  tab=config();
				tab.url=$this.attr('href');
				if(tab.url==''||tab.url.indexOf('javascript:')==0)
					return false;
				tab.id=$this.attr('rel');
				tab.title=$this.attr('title')?$this.attr('title'):$this.html();
				tab.iframe=$this.attr('iframe')==='true';
				$navTab.openTab(tab);
		    return false;
			})  
    },
	focus : function(){
		return $content.find('#' + curTab.id);
	},
    init:function(el,tabInfo){
    	$module = $(el);
      $ul = $module.find('.nav-tabs');
      $more = $module.find('.more'),
      $content = $module.find('.tab-content');
      methods.init(tabInfo);
    },
    openA: function(el,hideFlag){
    	$this=el;
    	var tab=config();
			tab.id=$this.attr('rel');
			tab.title=$this.attr('title')?$this.attr('title'):$this.html();
			tab.url=$this.attr('href');
			$navTab.openTab(tab,hideFlag);
    },
		openTab: function (tabInfo,hideFlag) {
			config(tabInfo);
			if(!hideFlag || hideFlag=='show') methods.hideTab();
			//var has = tabInfo.id in map;
			var has = methods.isTabExist(tabInfo.id);
 			if(has){
 				if(hideFlag=='hide') return;
 				curTab = map[tabInfo.id];
 				curTab.url=tabInfo.url;
 				curTab.formParams='';
 			}else{
 				var length  = Object.keys(map).length;
				if(length >= maxLength){
					$css.alert("最多可以打开"+maxLength+"个标签！");
					//alert("最多可以打开"+maxLength+"个标签！");
					$navTab.focus().show();
					return curTab;
				}
		    map[tabInfo.id]=tabInfo;
		    methods.initTab(tabInfo);
				methods.initClick(tabInfo);
			}
			if(!hideFlag || hideFlag=='show')  curTab=tabInfo;
		  methods.loadTab(tabInfo);
		  return tabInfo;
   	}, 
   	reloadTab: function(tabInfo,hideFlag){
   		var has  = tabInfo.id in map;
   		if(has){
   			map[tabInfo.id] = tabInfo;
   			var $curTab = $ul.find('[href="#'+tabInfo.id+'"]');
   			$curTab.find('span').text(tabInfo.title||tabInfo.text());
   			if(!hideFlag || hideFlag=='show')  curTab=tabInfo;
   			methods.loadTab(tabInfo);
   		}
   	},
    openTabById: function(tabId) {
 			if(!(tabId in map))	return '';
    	var tab = map[tabId];
    	$navTab.openTab(tab);
    },
    closeCurrentTab: function() {
    	$navTab.closeTab(curTab.id);
    },
	 	closeTab:function(tabId){
	    if(tabId == homeTabId) return;
 			if(!(tabId in map))	return;
	    var nextTabId=methods.getNextTab(tabId);
	    delete map[tabId];
		    $('#myTabli'+tabId).remove();
		    $('#moreBtnLi'+tabId).remove();
		    $('#'+tabId).remove();
		    if(nextTabId !='' && curTab.id==tabId){
			  	curTab=map[nextTabId];
			    methods.showTab();
			  }
		},
    refreshCurrentTab: function() {
    	methods.loadTab(curTab);
    },
    refreshTab: function(tabId) {
 			if(!(tabId in map))	return;
    	methods.hideTab();
 			curTab = map[tabId];
  		methods.loadTab(curTab);
    },
    refreshCurrentTabForm: function() {
    	var $form=$("#"+curTab.id).find('.table-form');
     	$navTab.submitForm($form[0]);
    },
    getCurrentTab: function() {
    	return curTab;
    },
    getTab: function(tabId) {
 			if(!(tabId in map))	return '';
    	return map[tabId];
    },
    submitForm: function(form){
    	//curTab.formParams=$(form).serialize();
		curTab.formParams=$(form).serializeParam(curTab.url);
  		$navTab.ajaxLoadForm($(form).attr('action'),$(form).serialize(),$(form).parent());
  		$(form).parent().scrollTop(0);
   	},
   	ajaxLoadForm: function(url, param, parent){
   		blockUI($content);
    	$.post(url,param,function(data){
			  parent.html(data);
			  $(parent).initUI();
			  unblockUI($content)
			})
    },
	clear : function(){
		map = {};
	}
  };
})(jQuery)